package com.sunchangpeng.server.nio.basic;

import com.sunchangpeng.server.bio.pool.TimeServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;

public class Dispatcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(TimeServer.class);

    private Selector selector;
    private Acceptor acceptor;
    private Handler handler;

    public void start(int port) {
        try {
            selector = Selector.open();
            acceptor = new Acceptor(selector);
            acceptor.start(port);
            handler = new Handler();
            LOGGER.info("dispatcher start in port:{}", port);
        } catch (IOException e) {
            LOGGER.error("", e);
            if (selector != null) {
                try {
                    selector.close();
                } catch (IOException ex) {
                    LOGGER.error("", ex);
                }
            }
        }
    }

    public void dispatch() {
        try {
            while (!Thread.interrupted()) {
                selector.select();
                Set<SelectionKey> selectedKeys = selector.selectedKeys();

                for (SelectionKey selectionKey : selectedKeys) {
                    if (selectionKey.isAcceptable()) {
                        acceptor.accept(selectionKey);
                    }

                    if (selectionKey.isReadable()) {
                        handler.handle(selectionKey);
                    }
                }

                selectedKeys.clear();
            }

        } catch (IOException e) {
            LOGGER.error("", e);
        } finally {
            if (selector != null) {
                try {
                    selector.close();
                } catch (IOException e) {
                    LOGGER.error("", e);
                }
            }
        }
    }
}
